package com.yxh.controller;

import com.github.pagehelper.PageInfo;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.yxh.common.annotation.Authorization;
import com.yxh.pojo.*;
import com.yxh.service.FlowManageService;
import com.yxh.service.ViciousService;
import com.yxh.util.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.druid.support.json.JSONUtils.toJSONString;
import static com.yxh.util.APIErrorCode.SUCCESS;

/**
 * Created by asus on 2018/6/5.
 */

@Scope("prototype")
@RestController
@RequestMapping(value = "/vicious")
public class  ViciousController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ViciousController.class);
    private Response response;


    @Autowired
    private ViciousService viciousService;



    @Autowired
    private TaskService taskService;

    @Autowired
    private FlowManageService flowManageService;

    /**
     *新增缺陷工单
     *
     * @param vicious
     * @return
     */

    @PostMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response saveVicious(@RequestBody Vicious vicious) {
        String id=SnowflakeIdWorker.creatId();
        int i=insertV(id,vicious);

        //启动流程

        Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("viciousId",id);//流程缺陷单
        variables.put("code",vicious.getViciousCode());
        variables.put("user",vicious.getUserId());//指定审核人


        flowManageService.start(variables,TaskCode.FAULT_KEY.getDesc(),TaskCode.OPERATION_MEG7.getDesc(),TaskCode.OPERATION_COMMENT7.getDesc());  //启动流程

        response = Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(i);
        return response;
    }

    /*
    * 监理录入 缺陷表单
    *
    *
    *
    * */
    @PostMapping("/super")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response saveViciouss(@RequestBody Vicious vicious) {
        String id=SnowflakeIdWorker.creatId();
        vicious.setType("2");
        vicious.setStatu(TaskCode.STATE_MEG5.getDesc());
        int i=insertV(id,vicious);

        //启动流程

        Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("viciousId",id);//流程缺陷单
        variables.put("user",vicious.getUserId());//指定审核人
        variables.put("user1",vicious.getLoggedUser());//指定审核人
        flowManageService.start(variables,TaskCode.SUPER_KEY.getDesc(),TaskCode.OPERATION_MEG7.getDesc(),TaskCode.OPERATION_COMMENT7.getDesc());  //启动流程

        response = Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(i);
        return response;
    }


    public int insertV(String id,Vicious vicious){

        vicious.setViciousId(id);
        vicious.setDay(DateUtils.parseDate(vicious.getDate()));

        int i=viciousService.save(vicious);
        //保存图片
        if(StringUtil.isNotEmpty(vicious.getImgsUrl())){
            flowManageService.insertImgs(vicious.getImgsUrl(),id);

        }

        History h=new History(); //存历史记录
        h.setUserid(vicious.getLoggedUser());
        h.setViciousId(id);
        h.setOperationName(TaskCode.OPERATION_COMMENT7.getDesc());
        i= viciousService.insertHistroy(h);
        return i;
    }



    /**
     *查询缺陷工单 分页
     *
     * @param vicious
     * @return
     */

    @GetMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response getInformation(Vicious vicious, String page, String pageSize) {
        Integer limit;
        Integer offset;
        try {
            limit = Integer.parseInt(page);
            offset = Integer.parseInt(pageSize);
        } catch (Exception e) {
            limit = 1;
            offset = 10;
        }
        if(vicious.getType()==null){
            vicious.setType("1");
        }
        vicious.setDay(DateUtils.parseDate(vicious.getDate()));
        PageInfo pageInfo = viciousService.getInformation(vicious, limit, offset);
        response = Response.returnResponse(SUCCESS);
        response.setData(pageInfo);
        return response;
    }

    @GetMapping("/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response getInformation(@PathVariable("id") String id) {


        response = Response.returnResponse(SUCCESS);
        response.setData(viciousService.get1(id));
        return response;
    }


    @GetMapping("/super/task/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response listsuper(@RequestParam(required = false, defaultValue = "1", name = "page") String page,
                         @RequestParam(required = false, defaultValue = "10", name = "pageSize") String pageSize,
                         @PathVariable(value = "id") String id) throws Exception {

        try {
            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(data(id,page,pageSize,TaskCode.SUPER_KEY.getDesc()));
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }

        return response;
    }

    @GetMapping("/task/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response list(@RequestParam(required = false, defaultValue = "1", name = "page") String page,
                         @RequestParam(required = false, defaultValue = "10", name = "pageSize") String pageSize,
                         @PathVariable(value = "id") String id) throws Exception {

        try {
            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(data(id,page,pageSize,TaskCode.FAULT_KEY.getDesc()));
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }

        return response;
    }

    public JSONObject data(String id,String page,String pageSize,String key ){

       //查询当前流程的任务
        List<Task> taskList= flowManageService.taskList(page,pageSize,id,key);

        List<MyTask> tasks = new ArrayList<MyTask>();

        for (Task task : taskList) {
            String viciousId= (String) taskService.getVariable(task.getId(), "viciousId");
            MyTask t = new MyTask();
            t.setId(task.getId());
            t.setName(task.getName());
            t.setCreateTime(task.getCreateTime());
            Map<String,Object> m=viciousService.get1(viciousId);
            t.setModel(m==null?new JSONObject():m);
            tasks.add(t);
        }
        //对数据进行转换
        JSONObject result=flowManageService.changeData(tasks,key,id);
        return result;
    }


    @PostMapping("/audit")
    // @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response audit(@RequestBody TaskParam param){
        Map<String, Object> variables = new HashMap<String, Object>();
        String  taskId=param.getTaskId(),viciousId= (String) taskService.getVariable(taskId, "viciousId"),
                megs="",operation="",ss="",imgs=param.getUrl();
        int state;
        try{
            state=param.getState();
        }catch(Exception e){
            state=0;
        }
        if(state!=0){

            operation=TaskCode.STATE_MEG17.getDesc();
            variables.put("meg", state);

            if (state == TaskCode.STATE_1.getValue()) {
                megs=TaskCode.STATE_MEG1.getDesc();
                ss=TaskCode.STATE_MEG4.getDesc();
            } else if (state == TaskCode.STATE_2.getValue()) {
                // 有缺陷进行处理 更新缺陷表  状态
                variables.put("user",param.getNextId());
                megs=TaskCode.STATE_MEG2.getDesc();
                ss=TaskCode.STATE_MEG5.getDesc();
            }
        }
      else{
            operation=TaskCode.STATE_MEG13.getDesc();
            megs=TaskCode.STATE_MEG3.getDesc();
           ss=TaskCode.STATE_MEG18.getDesc();
        }


        Vicious s=new Vicious();
        s.setViciousId(viciousId);
        s.setStatu(ss);
        int i= viciousService.update(s);

        History h=new History(); //存历史记录
        h.setUserid(param.getUserId());
        h.setViciousId(viciousId);
        h.setPresideId(param.getNextId());
        h.setComment(param.getComment());
        h.setState(megs);
        if(StringUtil.isNotEmpty(imgs)){
            String id= SnowflakeIdWorker.creatId();
            flowManageService.insertImgs(imgs,id);
            h.setImgId(id);
        }
        h.setOperationName(operation);
        i=viciousService.insertHistroy(h);

        //提交流程
        flowManageService.complete(taskId,variables,operation,megs);

        response= Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(i);
        return response;
    }


}
